<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #myCanvas{
      display: block;
      border: 1px solid #000;
      margin: 50px auto;
    }
    
  </style>
</head>
<body>
  <canvas width="500" height="500" id="myCanvas">
    当前版本浏览器不支持，请升级浏览器
  </canvas>
  <script>
    let canvas=document.getElementById('myCanvas');
    let ctx=canvas.getContext('2d');
    let ballArr=[];
    class Ball{
      constructor(x,y,r){
        this.x=x;
        this.y=y;
        this.r=r;
        this.color=this.getRandom();
        this.dx=parseInt(Math.random()*10)-5
        this.dy=parseInt(Math.random()*10)-5
        ballArr.push(this)
      }
      render(){
        ctx.beginPath()
        ctx.arc(this.x,this.y,this.r,Math.PI*2,false);
        ctx.fillStyle=this.color;
        ctx.fill()
      }
      update(){
        this.x+=this.dx;
        this.y+=this.dy;
        this.r-=0.3;
        
      }
      remove(){
        for(let i=0;i<ballArr.length;i++){
          if(ballArr[i]==this){
            ballArr.splice(i,1)
          }
        }
      }
      getRandom(){
        var allType="0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
        var allTypeArr=allType.split(',');
        var color="#";
        for(let i=0;i<6;i++){
          let random=parseInt(Math.random()*allTypeArr.length)
          color+=allTypeArr[random];
        }
        return color;
      }
    }
    canvas.addEventListener("mousemove",function (e) {
      new Ball(e.offsetX,e.offsetY,30)
    })
    setInterval(() => {
      ctx.clearRect(0,0,canvas.width,canvas.height);
      for(let i=0;i<ballArr.length;i++){
        ballArr[i].render()
        ballArr[i].update()
      }
    }, 10);

  </script>
</body>
</html>